package com.resourcestore.dao;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanMap;
import org.apache.log4j.Logger;

import com.ibatis.common.util.PaginatedList;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.resourcestore.utils.CommonUtil;
import com.resourcestore.utils.tag.Pagination;
import com.resourcestore.utils.SqlConfig;
public class BaseDao {
	
	SqlMapClient sqlMapper = null;
	
	protected Logger logger = null;
	
	protected static final int PAGE_SIZE = 15;
	
	public BaseDao(){
		getSqlMapper();
		getLogger();
	}
	
	/**
	 * 使用sql语句查询列表，返回List集合
	 * 
	 * @param sqlId
	 *            -- 待执行的sql查询语句，该sql语句存在于XML配置文件中，此处只需要引用相应的ID即可
	 * @return
	 */
	public List queryForList(String sqlId) {
		List<Object> results = null;
		try {
			results = sqlMapper.queryForList(sqlId);
		} catch (SQLException e) {
			printErrorInfo(e);
		}
		return results;
	}

	public List queryForList(String sqlId, Object parameterObject) {
		List<Object> results = null;
		try {
			results = sqlMapper.queryForList(sqlId, parameterObject);
		} catch (SQLException e) {
			printErrorInfo(e);
		}
		return results;
	}

	/**
	 * 查询出分页所需的10条数据（默认是 10条）
	 * 
	 * @param sqlId
	 * @param pagination
	 * @param parameterObject
	 * @return
	 */
	public List queryForPage(String sqlId, Object parameterObject,Pagination pagination) {
		List<Object> results = null;
		Map map = CommonUtil.changeBeanIntoMap(parameterObject);
		map = pagination.addStartNumRowNumToMap(map);
		results = this.queryForList(sqlId, map);
		return results;
	}

	/**
	 * 分页查询，所写sql语句中有where条件查询
	 * 
	 * @param sqlId
	 * @param parameterObject
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public PaginatedList queryForPaginatedList(String sqlId,
			Object parameterObject) {
		PaginatedList results = null;
		try {
			results = sqlMapper.queryForPaginatedList(sqlId, parameterObject,
					PAGE_SIZE);
		} catch (SQLException e) {
			printErrorInfo(e);
		}
		return results;
	}

	/**
	 * 分页查询，所写sql语句没有where条件
	 * 
	 * @param sqlId
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public PaginatedList queryForPaginatedList(String sqlId) {
		PaginatedList results = null;
		try {
			results = sqlMapper.queryForPaginatedList(sqlId, PAGE_SIZE);
		} catch (SQLException e) {
			printErrorInfo(e);
		}
		return results;
	}

	/**
	 * 向数据库执行插入操作
	 * 
	 * 
	 * @param sqlId
	 *            待执行的sql插入操作语句，该sql语句存在于XML配置文件中，此处只需要引用相应的ID即可
	 * @param parameterObject
	 *            待插入的对象
	 * @return 在配置文件中配置<selectKey>
	 */
	public void insert(String sqlId, Object parameterObject) {
		try {
			sqlMapper.insert(sqlId, parameterObject);
		} catch (SQLException e) {
			printErrorInfo(e);
		}
	}

	/**
	 * 向数据库执行插入操作，并返回配置文件中<selectKey>所返回的值
	 * 
	 * @param sqlId
	 * @param parameterObject
	 * @return
	 */
	public int insertAndReturnPK(String sqlId, Object parameterObject) {
		int returnValue = 0;
		try {
			returnValue = Integer.parseInt(sqlMapper.insert(sqlId,
					parameterObject).toString());
			// returnValue = Integer.parseInt((String)sqlMapper.insert(sqlId,
			// parameterObject)) ;
		} catch (SQLException e) {
			printErrorInfo(e);
		}
		return returnValue;
	}

	/**
	 * 向数据库执行修改操作
	 * 
	 * @param sqlId
	 *            待执行的sql修改操作语句，该sql语句存在于XML配置文件中，此处只需要引用相应的ID即可
	 * @param parameterObject
	 *            待修改的对象
	 * @return
	 */
	public void update(String sqlId, Object parameterObject) {
		try {
			sqlMapper.update(sqlId, parameterObject);
		} catch (SQLException e) {
			printErrorInfo(e);
		}

	}

	/**
	 * 向数据库执行删除操作
	 * 
	 * @param sqlId
	 *            待执行的sql删除操作语句，该sql语句存在于XML配置文件中，此处只需要引用相应的ID即可
	 * @param parameterObject
	 *            待删除的对象
	 */
	public void delete(String sqlId, Object parameterObject) {
		try {
			sqlMapper.delete(sqlId, parameterObject);
		} catch (SQLException e) {
			printErrorInfo(e);
		}
	}

	/**
	 * 查询数据库
	 * 
	 * @param sqlId
	 *            待执行的sql查询操作语句，该sql语句存在于XML配置文件中，此处只需要引用相应的ID即可
	 * @return 所查询表所对应的JAVA对象
	 */
	public Object queryForObject(String sqlId) {
		Object results = null;
		try {
			results = sqlMapper.queryForObject(sqlId);
		} catch (SQLException e) {
			printErrorInfo(e);
		}
		return results;
	}

	/**
	 * 查询数据库，当所写的查询语句中有where条件时，第二个参数parameterObject则对应上
	 * 
	 * @param sqlId
	 *            待执行的sql查询操作语句，该sql语句存在于XML配置文件中，此处只需要引用相应的ID即可
	 * @param parameterObject
	 * @return
	 */
	public Object queryForObject(String sqlId, Object parameterObject) {
		Object results = null;
		try {
			results = sqlMapper.queryForObject(sqlId, parameterObject);
		} catch (SQLException e) {
			printErrorInfo(e);
		}
		return results;
	}

	/**
	 * 分页查询，查询出每一页的数据
	 * 
	 * @param sqlId
	 * @param parameterObject
	 * @param startNum
	 * @return
	 */
	public List<?> queryForPagination(String sqlId, Object parameterObject,
			Pagination pager) {
		Map beanMap = new BeanMap(parameterObject);

		beanMap.put("startNum", pager.getCurrentRecord());
		beanMap.put("rows", pager.getPageLength());

		return (List<?>) this.queryForList(sqlId, beanMap);
	}

	/**
	 * 查询总数， 在xml中对应select count(*) from TABLE 的sql语句，sqlId即该语句对应的Id
	 * 
	 * @param sqlId
	 * @return
	 */
	public int queryNum(String sqlId, Object obj) {
		Object returnObj = this.queryForObject(sqlId, obj);
		if (null == returnObj)
			return 0;
		else
			return Integer.parseInt(returnObj.toString());
	}
	
	
	private SqlMapClient getSqlMapper() {
		if (null == sqlMapper) {
			sqlMapper = SqlConfig.getSqlMapInstatce();
		}
		return sqlMapper;
	}
	
	private Logger getLogger() {
		if (null == logger) {
			logger = Logger.getLogger(getClass().getName());
		}
		return logger;
	}
	
	/**
	 * 打印错误信息，以便于调试
	 * 
	 * @param e
	 */
	private void printErrorInfo(SQLException e) {
		logger.error("-----错误！-----" + "出现在类" + this.getClass() + "中，"
				+ "错误信息是：" + e.toString() + "，原因可能为：" + e.getCause()
				+ "，更加详细的错误信息：" + e.getMessage());
	}
}
